package com.sqin.taskflow.controller;


import com.sqin.taskflow.mapper.JobResultMapper;
import com.sqin.taskflow.model.JobResult;
import com.sqin.taskflow.model.ProcessRecord;
import com.sqin.taskflow.service.ProcessRecordService;
import com.sqin.taskflow.utils.flow.ImageService;
import com.sqin.taskflow.vo.JsonResult;
import com.sqin.taskflow.vo.QueryResult;
import com.sqin.taskflow.vo.Resp;
import liquibase.pro.packaged.J;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/task")
public class taskFlowController {

    @Resource
    private RepositoryService repositoryService;

    @Autowired
    private ProcessRecordService processRecordService;

    @Resource
    private RuntimeService runtimeService;

    @Resource
    private JobResultMapper jobResultMapper;

    @Resource
    private ImageService imageService;

    @GetMapping("/list")
    public JsonResult<QueryResult<ProcessRecord>> pageQuery(Integer page, Integer pageSize) {
        if (page == null) {
            page = 1;
        }
        if (pageSize == null) {
            pageSize = 10;
        }
        QueryResult<ProcessRecord> queryResult = processRecordService.pageQuery(page, pageSize);
        return Resp.ok(queryResult);
    }


    //  创建流程
    @PostMapping("/buffer")
    public JsonResult<Integer> buffer(@RequestBody ProcessRecord processRecord) {
        int count = processRecordService.save(processRecord);
        return Resp.ok(count);
    }

    /**
     * 删除流程定义
     *
     * @param id
     * @return
     */
    @DeleteMapping("/{id}/remove")
    public JsonResult<Integer> remove(@PathVariable("id") Integer id) {
        int count = processRecordService.remove(id);
        return Resp.ok(count);
    }

    /**
     * 流程发布和執行
     *
     * @param id
     * @return
     */
    @PutMapping("/{id}/deploy")
    public JsonResult deploy(@PathVariable("id") Integer id) {
        ProcessRecord processRecord = new ProcessRecord();
        processRecord.setId(id);
        processRecord.setDelFlag(false);
        ProcessRecord processRecordDB = processRecordService.selectOne(processRecord);

        repositoryService.createDeployment().
                addString(processRecordDB.getProcId()+".bpmn20.xml", processRecordDB.getXmlStr())
                .name(processRecordDB.getName())
                .key(processRecordDB.getProcId())
                .deploy();
        processRecord.setStatus((byte) 1);
        int modify = processRecordService.modify(processRecord);

        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processRecordDB.getProcId());

        processRecordDB.setProcInstId(processInstance.getProcessInstanceId());
        processRecordDB.setStatus((byte) 1);
        processRecordService.updateById(processRecordDB);

        return Resp.ok(modify);
    }


    @GetMapping("/{id}/image")
    public void getProcessImage(HttpServletResponse response, @PathVariable("id") String id) throws Exception{
        byte[] bytes = imageService.generateImageByProcInstId(id);
        response.setContentType("image/png");
        ServletOutputStream outputStream = response.getOutputStream();
        FileCopyUtils.copy(bytes,outputStream);
    }

    @GetMapping("/{id}/result")
    public JsonResult getProcessResult(HttpServletResponse response, @PathVariable("id") String id){
        List<JobResult> jobResultList =  jobResultMapper.selectByProcId(id);
        return Resp.ok(jobResultList);
    }

    @GetMapping("/retry/{id}")
    public JsonResult getRetry(HttpServletResponse response, @PathVariable("id") String id){
        List<JobResult> jobResultList =  jobResultMapper.selectByProcId(id);
        return Resp.ok(jobResultList);
    }



//  流程列表

//  启动流程

//  流程状态

//  流程结果查询

}
